﻿using PetaPoco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Bootstrap.Security.DataAccess
{
    /// <summary>
    /// PetaPoco ORM 数据库映射类
    /// </summary>
    internal class BootstrapAdminConventionMapper : ConventionMapper
    {
        private readonly Dictionary<Type, TableInfo> _tableInfos;
        private readonly Dictionary<Type, IEnumerable<string>> _ignoreColumns;
        private readonly Dictionary<Type, IEnumerable<string>> _resultColumns;

        /// <summary>
        /// 构造函数
        /// </summary>
        public BootstrapAdminConventionMapper()
        {
            _tableInfos = new Dictionary<Type, TableInfo>
            {
                { typeof(BootstrapDict), new TableInfo() { TableName = "Dicts", PrimaryKey = "Id", AutoIncrement = true } },
                { typeof(BootstrapMenu), new TableInfo() { TableName = "Navigations", PrimaryKey = "Id", AutoIncrement = true } },
                { typeof(BootstrapGroup), new TableInfo() { TableName = "Groups", PrimaryKey = "Id", AutoIncrement = true } },
                { typeof(BootstrapUser), new TableInfo() { TableName = "Users", PrimaryKey = "Id", AutoIncrement = true } }
            };

            _ignoreColumns = new Dictionary<Type, IEnumerable<string>>
            {
                { typeof(BootstrapMenu), new string[] { "Menus" } }
            };

            _resultColumns = new Dictionary<Type, IEnumerable<string>>
            {
                { typeof(BootstrapMenu), new string[] { "ParentName", "Active", "CategoryName" } }
            };
        }

        /// <summary>
        /// 通过属性获取列信息
        /// </summary>
        /// <param name="pocoProperty"></param>
        /// <returns></returns>
        public override ColumnInfo GetColumnInfo(PropertyInfo pocoProperty)
        {
            if (_ignoreColumns.TryGetValue(pocoProperty.DeclaringType, out var ignoreColumns) && ignoreColumns.Any(c => c.Equals(pocoProperty.Name, StringComparison.OrdinalIgnoreCase))) return null;
            var ci = new ColumnInfo() { ColumnName = pocoProperty.Name };
            if (_resultColumns.TryGetValue(pocoProperty.DeclaringType, out var resultColumns) && resultColumns.Any(c => c.Equals(pocoProperty.Name, StringComparison.OrdinalIgnoreCase))) ci.ResultColumn = true;
            return ci;
        }

        /// <summary>
        /// 通过类型获取表信息
        /// </summary>
        /// <param name="pocoType"></param>
        /// <returns></returns>
        public override TableInfo GetTableInfo(Type pocoType) => _tableInfos[pocoType];
    }
}
